/* 读取多个文件 */

%option noyywrap

%{
    int chars = 0;
    int words = 0;
    int lines = 0;

    int totchars = 0;
    int totwords = 0;
    int totlines = 0;
%}

%%

[a-zA-Z]+ { words++; chars += strlen(yytext); }
\n { chars++; lines++; }
. { chars++; }

%%

int main(int ac, char** av) {
    int i;
    if (ac < 2) { // read stdin
        yylex();
        printf("%8d%8d%8d\n", lines, words, chars);
        return 0;
    }

    for (i=1; i<ac; i++) {
        FILE* f = fopen(av[i], "r");
        if (!f) {
            perror(av[i]);
            return 1;
        }

        // 把打开的文件作为词法分析器的输入
        yyrestart(f);
        yylex();
        printf("%8d%8d%8d %s\n", lines, words, chars, av[i]);

        totchars += chars; chars = 0;
        totwords += words; words = 0;
        totlines += lines; lines = 0;
    }
    if (ac > 1) {
        printf("%8d%8d%8d total\n", totlines, totwords, totchars);
    }
    return 0;
}

